<?php
class JExtMenu extends CWidget {

	public $items;

	public function init() {
		parent::init();
	}
	public function run() {
		$items = $this->items;
		$itemsJs = CJavaScript::encode($this->parseItemsRecursive($items));
		$script = <<<EOF
		Ext.onReady(function(){
			var createRedirect=function(url){
				return function(){
					window.location.href=url;
				}
			}
		Ext.create('Ext.toolbar.Toolbar', {
		            layout: {
		                overflowHandler: 'Menu'
		            },
		            renderTo: 'action-menu',
		            items: /*[{
		                xtype:'splitbutton',
		                text: 'Menu Button',
		                iconCls: 'add16',
		                menu: [{text: 'Menu Item 1', handler: Ext.Function.pass(handleAction, 'Menu Item 1')}]
		            }]*/ $itemsJs
		        });
		});
EOF
		;

		Yii::app()->clientScript->registerScript('action-menu', $script, CClientScript::POS_END);
		echo '<div id="action-menu"></div>';
	}

	protected function parseItemsRecursive($items) {
		$result = array();
		if (!is_array($items) || empty($items)) {
			return $result;
		}
		foreach ($items as $item) {
			$item = $this->parseSingleItem($item);
			if ($item !== null) {
				$result[] = $item;
			}
		}
		return $result;
	}

	protected function parseSingleItem($item) {
		$result = array();
		if (!isset($item['label']) && !isset($item['iconCls'])) {
			return null;
		}
		if (isset($item['visible']) && !$item['visible']) {
			return null;
		}
		if (isset($item['label'])) {
			$result['text'] = $item['label'];
		}
		if (isset($item['iconClass'])) {
			$result['iconCls'] = $item['iconClass'];
		}
		if (isset($item['url'])) {
			$url = $this->getController()
				->createUrl($item['url'][0], array_splice($item['url'], 1));
			$result['handler'] = 'js:createRedirect(' . CJSON::encode($url) . ')';
		}
		if (isset($item['items'])) {
			$subMenu = $this->parseItemsRecursive($item['items']);
			if (!empty($subMenu)) {
				$result['menu'] = $subMenu;
				//$result['xtype'] = 'splitbutton';
			} else {
				if (!isset($item['url'])) {
					return null;
				}
			}
		}
		return $result;
	}
}
